console.log('popup.js');


// 显示结果的函数
function showResults(resultItem) {
    chrome.storage.local.set({ elementData: resultItem }, function () {
        console.log('Data is saved');
    });
    // 将结果渲染到页面上，例如使用 JSON.stringify 将结果转换为字符串
    var $table = $('#dataTable > tbody');
    $('#dataTable > tbody').empty();
    $table.append("<tr><td>用户(device_id)            </td><td>" + resultItem.user.device_id + "</td></tr>");
    $table.append("<tr><td>国家(country_code)         </td><td>" + resultItem.user.country_code + "</td></tr>");
    $table.append("<tr><td>出生(year_of_birth)        </td><td>" + resultItem.user.year_of_birth + "</td></tr>");
    $table.append("<tr><td>语言(spoken_languages)     </td><td>" + resultItem.user.spoken_languages + "</td></tr>");
    $table.append("<tr><td>性别(gender)               </td><td>" + resultItem.user_str.gender + "</td></tr>");
    $table.append("<tr><td>邮编(zip_code)             </td><td>" + resultItem.user.postal_data + "</td></tr>");
    $table.append("<tr><td>婚姻(marital_status)       </td><td>" + resultItem.user_str.marital_status + "</td></tr>");
    $table.append("<tr><td>孩子(parental)             </td><td>" + resultItem.user_str.parental + "</td></tr>");
    $table.append("<tr><td>教育(education)            </td><td>" + resultItem.user_str.education + "</td></tr>");
    $table.append("<tr><td>就业(employment)           </td><td>" + resultItem.user_str.employment + "</td></tr>");
    $table.append("<tr><td>行业(career)               </td><td>" + resultItem.user_str.career + "</td></tr>");
    $table.append("<tr><td>种族(ethnicity)            </td><td>" + resultItem.user_str.race + "</td></tr>");
    $table.append("<tr><td>收入(income)               </td><td>" + resultItem.user_str.income + "</td></tr>");
    $table.append("<tr><td>角色(organization_role)    </td><td>" + resultItem.user_str.organization_role + "</td></tr>");
    $table.append("<tr><td>员工数(number_of_employees)</td><td>" + resultItem.user_str.number_of_employees + "</td></tr>");

}

var data = ""
// 假设这是你的插件的 background.js 文件// 插件初始化时执行的函数function initPlugin() {
// 发送请求到远程服务器获取数据
async function initPlugin() {
    chrome.runtime.sendMessage({ action: "getFirstTabTitle" }, (response) => {
        if (response && response.title) {
            var title = response.title;
            fetch('https://itdajie.com/pollfish/user/' + title.split("-")[2])
                .then(response => response.json()) // 将响应解析为JSON
                // .then(response => console.log(response)) // 将响应解析为JSON
                .then(data => {
                    console.log("initPlugininitPlugininitPlugininitPlugininitPlugin")
                    showResults(data);
                    console.log("document.currentUrl")
                    for (var i = 0; i < chrome.tabs.length; i++) {
                        alert(chrome.tabs[i])
                    }

                    console.log("document.currentUrl")
                    // sessionStorage.setItem('remoteData', JSON.stringify(data));
                    sessionStorage.setItem('remoteData', "123");

                    // 你可以在这里执行其他操作，比如更新UI等
                    data = sessionStorage.getItem('remoteData');
                })
                .catch(error => {
                    // 处理请求错误
                    console.error('Error fetching remote data:', error);
                });
            chrome.storage.local.set({ "title": title }, function () {
                console.log('Data is saved');

            });
        } else {
            alert("No tabs found")
        }
    });

}

// 调用函数
$(document).ready(function () {
    initPlugin();

});

// document.addEventListener('DOMContentLoaded', () => {

// });




document.addEventListener('DOMContentLoaded', function () {



    document.getElementById('add_user_button').addEventListener('click', function () {
        // 向目标页面发送消息以获取数据
        console.log('popup 发送消息出去 add_user_button ，要自动添加用户');
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            chrome.scripting.executeScript({
                target: { tabId: tabs[0].id },
                function: function () {

                    const currentUrl = document.URL;

                    chrome.storage.local.set({ 'currentUrl': currentUrl }, function () {
                        chrome.runtime.sendMessage({ 'action': 'add_user_button' }, (response) => {
                            if (!(response && response.result)) {
                                console.log('popup 接收到错误消息：', response);
                                return;
                            }
                            console.log("使用 fetch 发出 PUT 请求")
                            var data = response.result
                            console.log('popup 接收到正确消息：', response.result);
                            ////////////////////////////// 循环处理答题 //////////////////////////////////////////////////
                            let timeLeft = 300; // 等待时间
                            const intervalId = setInterval(() => {
                                ///////////// 第一步：做一个简单提示 //////
                                var element = document.getElementById("submit-btn");
                                if (!element) {
                                    var element = document.getElementById("take-survey-btn");
                                }
                                if (!element) {
                                    var element = document.getElementsByClassName("btn btn-primary btn-lg")[0]
                                }

                                timeLeft--;
                                element.textContent = timeLeft + "秒后提交";
                                ///////////// 第二步：当等待时间耗尽时，执行 //////
                                if (timeLeft <= 0) {
                                    clearInterval(intervalId);
                                }
                                ///////////// 第三步：每5秒一个题 //////
                                if (timeLeft % 10 == 0) {
                                    element.textContent = "开始答题";
                                    // var main_content_home_el = document.querySelector("#wrapper > div > main > div > div.main-content__home > h1")
                                    // var main_content_home_el = document.querySelector("#wrapper > div > main > div > div > div.loading__header > h1")

                                    var main_content_home_el = document.querySelectorAll('#rating-container > div.margin-lg-btm > span');
                                    
                                    



                                    const question_element = document.getElementsByClassName("js-question question__text")[0];
                                    if (question_element) {
                                        var question_element_id = question_element.attributes["id"].value
                                    } else if (main_content_home_el) {
                                        var question_element_id = 'thank_your'
                                    }
                                    // else if (main_content_home_el) {
                                    //     var question_element_id = 'Share your opinion on things that matter!'
                                    // } 
                                    else {
                                        var question_element_id = "-";
                                    }

                                    switch (question_element_id) {
                                        case "Share your opinion on things that matter!":
                                            console.log("Share your opinion on things that matter!");
                                            var take_survey_btn = document.getElementById("take-survey-btn")
                                            // 设置 tabindex，使 <a> 标签能够接收焦点
                                            take_survey_btn.setAttribute('tabindex', '0');

                                            // 模拟焦点到元素上
                                            take_survey_btn.focus();


                                            setTimeout(function () { take_survey_btn.click() }, 5000); // 5秒后执行
                                            break;
                                        case "1": // id=1 性别
                                            console.log("It's 1:" + response.result.elementData.user.gender);
                                            var id = response.result.elementData.user.gender;
                                            if (id == 1) { //1:"34180|Female|女性",
                                                id = 1
                                            } else if (id == 2) {//2:"34179|Male|男性",
                                                id = 0
                                            } else {
                                                id = 2 //3:"54730|Other|其他",
                                            }
                                            break;
                                        case "2": // id=2 生日
                                            var inputElement = document.querySelector('input'); // 获取 input 元素
                                            text = '' + response.result.elementData.user.year_of_birth // 模拟逐字输入
                                            delay = 100
                                            inputElement.value = ''; // 清空输入框内容
                                            var event = new Event('input', {// 触发清空后的 input 事件
                                                bubbles: true,
                                                cancelable: true
                                            });
                                            inputElement.dispatchEvent(event); // 触发 input 事件
                                            var index = 0;
                                            function inputNextChar() {
                                                if (index < text.length) {
                                                    inputElement.value += text[index]; // 添加下一个字符到输入框
                                                    var event = new Event('input', {// 创建并触发 input 事件
                                                        bubbles: true,
                                                        cancelable: true
                                                    });
                                                    inputElement.dispatchEvent(event); // 触发 input 事件
                                                    index++;
                                                    setTimeout(inputNextChar, delay); // 递归调用下一个字符，延迟 delay 毫秒
                                                }
                                            }
                                            inputNextChar(); // 开始逐字输入
                                            break;
                                        case "3": // id=3 结婚状态
                                            console.log("It's 3:" + response.result.elementData.user_str.marital_status);
                                            var id = response.result.elementData.user.marital_status
                                            if (id == 0) { //0:"34282|Single|单身的",
                                                id = 3
                                            } else if (id == 1) { //1:"34284|Married|已婚",
                                                id = 5
                                            } else if (id == 2) { //2:"34279|Divorced|离婚",
                                                id = 0
                                            } else if (id == 3) {//3:"34280|Living with partner|与伴侣同住",
                                                id = 1
                                            } else if (id == 4) {//4:"34281|Separated|分居",
                                                id = 2
                                            } else if (id == 5) {//5:"34283|Widowed|丧偶",
                                                id = 4
                                            } else if (id == 6) {//6:"34285|Prefer not to say|宁愿不说",
                                                id = 6
                                            }
                                            break;
                                        case "4": // id=4 孩子
                                            console.log("It's 4:" + response.result.elementData.user_str.parental);
                                            var id = response.result.elementData.user.parental
                                            break;
                                        case "5": // id=5 教育程度
                                            console.log("It's 5:" + response.result.elementData.user_str.education);
                                            var id = response.result.elementData.user.education - 1
                                            break;
                                        case "6": // id=6 就业情况
                                            console.log("It's 6:" + response.result.elementData.user_str.employment);
                                            var id = response.result.elementData.user.employment
                                            break;
                                        case "7": // id=7 就业情况
                                            console.log("It's 7:" + response.result.elementData.user_str.career);
                                            var id = response.result.elementData.user.career
                                            if (id < 16) { //不变
                                                id = id;
                                            } else if (id > 16 && id < 22) {
                                                id = id - 1;
                                            } else if (id > 22 && id < 25) {
                                                id = id - 2;
                                            } else if (id > 25 && id < 28) {
                                                id = id - 3;
                                            } else if (id > 28 && id < 31) {
                                                id = id - 4;
                                            } else if (id > 31) {
                                                id = id - 5;
                                            } else if (id == 31) {
                                                id = 37;
                                            }
                                            break;
                                        case "8":
                                            console.log("It's 8:" + response.result.elementData.user_str.race);
                                            var id = response.result.elementData.user.race
                                            break;
                                        case "9":
                                            console.log("It's 9:" + response.result.elementData.user_str.income);
                                            var id = response.result.elementData.user.income
                                            break;
                                        case "11":
                                            console.log("It's 11:" + response.result.elementData.user_str.organization_role);
                                            var id = response.result.elementData.user.organization_role
                                            if (id < 12) {
                                                id = id;
                                            } else if (id > 12 && id < 19) {
                                                id = id - 1;
                                            } else if (id > 19 && id < 23) {
                                                id = id - 2;
                                            } else if (id == 24) {
                                                id = id - 3;
                                            }
                                            break;
                                        case "12":
                                            console.log("It's 12:" + response.result.elementData.user_str.number_of_employees);
                                            var id = response.result.elementData.user.number_of_employees
                                            break;
                                        case "13":
                                            break;
                                        case "2138":
                                            timeLeft = timeLeft + 10
                                            break;
                                        case "thank_your":

                                            // 使用 URL 构造函数创建一个 URL 对象
                                            const urlObj = new URL(response.result.currentUrl);
                                            var url_json_str = urlObj.searchParams.get("json")
                                            var url_json_obj = JSON.parse(url_json_str)
                                            var new_device_id = url_json_obj.device_id
                                            chrome.runtime.sendMessage({ 'action': 'thank_your', 'new_device_id': new_device_id, "result": response.result }, (response) => {
                                                if (response) {
                                                    alert('数据存储完成');
                                                    alert(response)
                                                    return;
                                                }
                                            })
                                            timeLeft = 0
                                            break;
                                        default:
                                            // alert(question_element_id)
                                            alert('question_element not found.' + question_element_id);
                                    }
                                    if (question_element_id == '2138') {
                                        console.log(question_element_id)
                                    } else if (document.getElementById("submit-btn")) {
                                        var labels = document.querySelectorAll('.answer--single-choice');
                                        if (labels && labels.length > 0 && question_element_id!='2') {
                                            var element = labels[id]
                                            element.click();
                                            element.classList.add("answerClick");
                                        }
                                        setTimeout(function () { document.getElementById("submit-btn").click() }, 5000); // 5秒后执行

                                    }
                                }
                            }, 1000);


                        });
                    });
                }

            });
        });



    });




})




// document.querySelector("#wrapper > div > main > div > div > div.loading__header > h1").innerText="'Thank you 谢谢'"